'use client';
import { EventSourceConfig, EventData } from './Events';

const DEFAULT_CONFIG: EventSourceConfig = {
  reconnectInterval: 5000,
  maxRetries: 3
};

let eventSources: { [key: string]: any } = {};

export function useListener(channel: string, onMessage: (data: EventData) => void, config: EventSourceConfig = DEFAULT_CONFIG): () => void {
  if (typeof window === 'undefined') {
    return () => {};
  }

  // 如果已有连接，则关闭
  if (eventSources[channel]) {
    eventSources[channel].close();
    delete eventSources[channel];
  }

  try {
    const EventSourceCtor = window.EventSource;
    if (!EventSourceCtor) {
      console.error('EventSource 不支持');
      return () => {};
    }

    const es = new EventSourceCtor('/api/sse?channel=' + encodeURIComponent(channel));
    eventSources[channel] = es;

    es.onopen = () => {
      // SSE 连接已建立
    };

    es.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        onMessage(data);
      } catch (error) {
        console.error('解析 SSE 消息失败:', error);
      }
    };

    es.onerror = (error) => {
      console.error(`SSE 连接错误，频道: ${channel}`, error);
      es.close();
      delete eventSources[channel];
    };

    return () => {
      if (eventSources[channel]) {
        eventSources[channel].close();
        delete eventSources[channel];
      }
    };
  } catch (error) {
    console.error('建立 SSE 连接失败:', error);
    return () => {};
  }
}
